package cn.rkylin.oms.common.context;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.rkylin.oms.common.utils.CookieUtil;
import cn.rkylin.oms.common.utils.RedisUtils;
import cn.rkylin.oms.system.project.vo.ProjectVO;

/**
 * 缺省上下文实现
 * 
 * @author wangxiaoyi
 * @version 1.0
 * @since 2017年2月15日
 */
public class DefaultWebContext implements IWebContext, Serializable {
    private static final long serialVersionUID = -8987325667454341833L;
    private static final Log logger = LogFactory.getLog(DefaultWebContext.class);
    private CurrentUser currentUser;
    private CookieUtil cookieUtil = new CookieUtil();
    /**
     * 首页切换的当前项目
     */
    private ProjectVO currentProject;
    
    /**
     * 设置当前用户，并同步到缓存中
     * 
     * user不为空，则是设置用户
     * user为空，则是退出登录，清除当前用户缓存
     */
    public void setCurrentUser(CurrentUser user) {
        //currentUser变更，把自身 放入缓存
        String sessionId = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getSessionId();
        // 登录后放缓存
        if (user != null && StringUtils.isNotBlank(user.getAccount())) {
            RedisUtils.set("user:" + user.getAccount(), user, null);
            this.currentUser = user;
            // 18个小时后缓存自动删除
            long Time = System.currentTimeMillis() + (60 * 60 * 18 * 1000);
            Date expireTime =new Date(Time);
            RedisUtils.set(sessionId, this, expireTime);
        } else if (user == null) {
            RedisUtils.del(sessionId);
        }
        this.currentUser = user;
    }

    /**
     * 根据当前cookie获取当前用户
     */
    public CurrentUser getCurrentUser() {
        if (this.currentUser != null) {
            return this.currentUser;
        }
        // 未登录，从cookie中取上次登录成功的user
        CookieUtil cookieUtil = new CookieUtil();
        CurrentUser cookieUser = cookieUtil.getCurrentUserCookie();
        Cookie rememberMe = cookieUtil.getCookie("rememberMe");
        if (cookieUser != null && StringUtils.isNotBlank(cookieUser.getAccount()) 
                && rememberMe != null && rememberMe.getValue().equalsIgnoreCase("true")) {
            this.currentUser = RedisUtils.get("user:" + cookieUser.getAccount(), CurrentUser.class);
            
            // cookie登录后，构造会话的上下文
            IWebContext webContext = WebContextFactory.getWebContext();
            if (webContext != null && this.currentUser != null) {
                webContext.setCurrentUser(this.currentUser);
                Cookie currentProjectCookie = cookieUtil.getCookie("currentProjectId");
                if (currentProjectCookie != null && StringUtils.isNotEmpty(currentProjectCookie.getValue())) {
                    String projectId = currentProjectCookie.getValue().trim();
                    Map<String, ProjectVO> projectMap = this.currentUser.getProjectMap();
                    if (projectMap != null && projectMap.containsKey(projectId)) {
                        webContext.setCurrentProject(projectMap.get(projectId));
                    }
                } else {
                    // 没有cookie oh my!
                    Map<String, ProjectVO> prjectMap = this.currentUser.getProjectMap();
                    if (prjectMap != null && prjectMap.size() > 0) {
                        webContext.setCurrentProject(prjectMap.values().iterator().next());
                    } else {
                        // TODO 没有任何项目权限
                    }
                }
            }
            return currentUser;
        }
        return this.currentUser;
    }

    @Override
    public String getHost() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRemoteHost();
    }

    @Override
    public String getRemoteAddr() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRemoteAddr();
    }

    @Override
    public Cookie getCookie(String cookieName) {
        return cookieUtil.getCookie(cookieName);
    }

    @Override
    public String getCookieValue(String cookieName) {
        Cookie cookie = getCookie(cookieName);
        return cookie == null ? "" : cookie.getValue();
    }

    @Override
    public Cookie[] getCookies() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getCookies();
    }

    @Override
    public void setCookie(Cookie c) {
        cookieUtil.saveCookies(false, 0);;
    }

    @Override
    public void expireCookie(String cookieName) {
        cookieUtil.removeCookie(cookieName);
    }
    
    public ProjectVO getCurrentProject() {
        return currentProject;
    }

    public void setCurrentProject(ProjectVO currentProject) {
        this.currentProject = currentProject;
        
        String sessionId = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getSessionId();
        // 18个小时后缓存自动删除
        long Time = System.currentTimeMillis() + (60 * 60 * 18 * 1000);
        Date expireTime =new Date(Time);
        RedisUtils.set(sessionId, this, expireTime);
    }
//    public boolean checkValidateCode(String input, boolean remove) {
//        String validateCode = (String) session.getAttribute(Global.VALIDATE_CODE);
//        boolean result = StringUtils.equals(validateCode, input);
//        if (remove || result) {
//            session.removeAttribute(Global.VALIDATE_CODE);
//        }
//        return result;
//    }

}
